package com.lzht.games.room.stream;

import com.alibaba.fastjson.JSONObject;
import com.lzht.games.common.common.BasicMsg;
import com.lzht.games.common.common.NotifyMsg;
import com.lzht.games.common.common.ResponseMsg;
import com.lzht.games.common.constant.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.binding.BinderAwareChannelResolver;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * Create by weishuaiding on 2018/12/5 15:04
 */
@Component
public class DynamicSendService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private BinderAwareChannelResolver resolver;

    public <T> void send(String topic, T message) {
        logger.info("发送动态topic消息：{}, topic:{}", message, topic);
        resolver.resolveDestination(topic).send(MessageBuilder.withPayload(message).build());
    }

    public void response(BasicMsg resp, String requestId, NotifyMsg<JSONObject> notify) {
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg.ok(resp, requestId);

        JSONObject object = (JSONObject) JSONObject.toJSON(responseMsg);
        NotifyMsg<JSONObject> notifyClone = notify.clone();
        notifyClone.setNotifyData(object);
        send(notify.getHeader().getAccessId(), notifyClone);
    }

    public void responseError(BasicMsg resp, String requestId, NotifyMsg<JSONObject> notify, Results result) {
        ResponseMsg responseMsg = new ResponseMsg();
        responseMsg.error(result, resp, requestId);

        JSONObject object = (JSONObject) JSONObject.toJSON(responseMsg);
        NotifyMsg<JSONObject> notifyClone = notify.clone();
        notifyClone.setNotifyData(object);
        send(notify.getHeader().getAccessId(), notifyClone);
    }
}
